package middlewere

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"yzy6.26exam/golbal"
)

func UserAuthMiddleWere() gin.HandlerFunc {
	return func(context *gin.Context) {
		token := context.Request.Header.Get("token")
		if token == "" {
			context.AbortWithStatusJSON(http.StatusOK, gin.H{
				"code":    251,
				"message": "未登录",
			})
			return
		}
		ids, err := golbal.RDB.Get(golbal.Ctx, fmt.Sprintf("user:token:%s", token)).Result()
		id, _ := strconv.Atoi(ids)
		if err != nil {
			context.AbortWithStatusJSON(http.StatusOK, gin.H{
				"code":    252,
				"message": "登录失效",
			})
			context.Abort()
			return
		}
		context.Request.ParseForm()
		context.Request.Form.Set("user_id", fmt.Sprintf("%d", id))
		fmt.Println("user:", id)
		context.Next()
	}
}
